package com.learn.core.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.JwtUtil;
import com.learn.common.utils.PageResult;
import com.learn.common.utils.ResultUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.LCompetitionSort;
import com.learn.core.dto.LCompetitionSortDTO;
import com.learn.core.service.ILCompetitionSortService;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName LQuestionsSortController
 * @date 2021.03.22 09:42
 * @describe 竞赛分类
 */
@Api("竞赛分类")
@RestController
@RequestMapping("/manager/competitionSort")
public class LCompetitionSortController extends WebController<LCompetitionSort> {

    @Autowired
    private ILCompetitionSortService ilCompetitionSortService;

    //试题分类树
    @ApiOperation(value = "竞赛分类树")
    @UserLoginToken
    @PostMapping("/tree")
    public CommonResult<Object> tree(){
        try {
            QueryWrapper<LCompetitionSort> queryWrapper = new QueryWrapper<LCompetitionSort>();
            List<LCompetitionSort> lCompetitionSorts = ilCompetitionSortService.queryLCompetitionSortAll(queryWrapper);
            if(lCompetitionSorts.size()>0)
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lCompetitionSorts);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //列表
    @ApiOperation(value = "获取竞赛分类列表")
    @UserLoginToken
    @PostMapping("/list")
    public PageResult<LCompetitionSort> list(@RequestBody LCompetitionSortDTO lCompetitionSortDTO){
        try {
            if (lCompetitionSortDTO==null||lCompetitionSortDTO.getPage()==null||lCompetitionSortDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCompetitionSortDTO.getPage(),lCompetitionSortDTO.getRows());
            QueryWrapper<LCompetitionSort> queryWrapper = new QueryWrapper<LCompetitionSort>();
            if(lCompetitionSortDTO.getParentNode()!=null)
                queryWrapper.eq("parent_node",lCompetitionSortDTO.getParentNode());
            else {
                queryWrapper.eq("parent_node","0");
            }
            if(lCompetitionSortDTO.getCompetitionSortName()!=null)
                queryWrapper.like("competition_sort_name",lCompetitionSortDTO.getCompetitionSortName());
            Page<LCompetitionSort> lCompetitionSorts = (Page<LCompetitionSort>) ilCompetitionSortService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lCompetitionSorts)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(lCompetitionSorts.getTotal(), lCompetitionSorts, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }


    //新增
    @ApiOperation(value = "添加")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加竞赛分类", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LCompetitionSort lCompetitionSort, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lCompetitionSort!=null) {
                if (StringUtils.isEmpty(lCompetitionSort.getCompetitionSortName())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_QUESTIONS_SORT_NAME);
                }
                if (StringUtils.isEmpty(lCompetitionSort.getParentNode())) {
                    lCompetitionSort.setParentNode(0);
                }

                lCompetitionSort.setCreateTime(new Date());
                lCompetitionSort.setCreateUser(userId);
                if (ilCompetitionSortService.save(lCompetitionSort)) {
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }


    //删除
    @ApiOperation(value = "删除")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除竞赛分类", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LCompetitionSort lCompetitionSort){
        try {
            if(lCompetitionSort!=null){
                if(lCompetitionSort.getCompetitionSortId()!=null){
                    List<Integer> ids = new ArrayList<>();
                    ids.add(lCompetitionSort.getCompetitionSortId());
                    if(nodeStr(ids)){
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    private Boolean nodeStr (List<Integer> lists) throws Exception{
        List<Integer> ids = new ArrayList<>();
        QueryWrapper<LCompetitionSort> queryWrapper = new QueryWrapper<LCompetitionSort>();
        for (int i = 0; i <lists.size() ; i++) {
            int orgid = lists.get(i);

            queryWrapper.eq("parent_node",orgid);
            List<LCompetitionSort> lCompetitionSorts = ilCompetitionSortService.list(queryWrapper);
            for (int j = 0; j < lCompetitionSorts.size(); j++) {
                LCompetitionSort lCompetitionSort = lCompetitionSorts.get(j);
                ids.add(lCompetitionSort.getCompetitionSortId());
            }
        }
        if(ids.size() > 0){
            this.nodeStr(ids);
        }

        ids.addAll(lists);
        queryWrapper = new QueryWrapper<LCompetitionSort>();
        queryWrapper.in(true, "competition_sort_id", ids);
        ilCompetitionSortService.remove(queryWrapper);

        return Boolean.TRUE;
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新竞赛分类", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LCompetitionSort lCompetitionSort, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        if(lCompetitionSort!=null){
            lCompetitionSort.setUpdateTime(new Date());
            lCompetitionSort.setUpdateUser(userId);
            if(ilCompetitionSortService.updateById(lCompetitionSort)){
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}
